package com.h2cloud.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.h2cloud.entity.BaseResp;
import com.h2cloud.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackageName: com.h2cloud.interceptor
 * @ClasssName: MyInterceptor
 * @Author: h2cloud
 * @Date: 2021/3/10 13:01
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String errorInfo;
        // 获取请求中的 token
        try {
            String token = request.getHeader("Authorization");
            System.out.println("============preHandle Authorization = " + token);
            JWTUtil.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            errorInfo = "无效签名";
        } catch (TokenExpiredException e) {
            errorInfo = "token过期";
        } catch (AlgorithmMismatchException e) {
            errorInfo = "token算法不一致！";
        } catch (Exception e) {
            errorInfo = "token无效！";
        }

        returnJson(response, errorInfo);
        return false;
    }

    public void returnJson(HttpServletResponse response, String errorInfo) throws IOException {
        System.out.println("errorInfo = " + errorInfo);
        BaseResp baseResp = new BaseResp();

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");

        baseResp.setCode(301);
        baseResp.setMsg(errorInfo);
        System.out.println(JSON.toJSONString(baseResp));
        response.getWriter().println(JSON.toJSONString(baseResp));

        System.out.println("token 错误");
    }
}
